package org.example.myspringbootproject01.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.myspringbootproject01.utils.ResultUtils;
import org.example.myspringbootproject01.utils.ResultVo;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class ImgController {
    @PostMapping
    public ResultVo UploadPic(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws FileNotFoundException {
        try{
            System.out.println("接收文件" + file.getOriginalFilename());
            SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy-MM-dd/");
            String filename = file.getOriginalFilename();//取得文件名称
            if (!filename.endsWith(".png") && !filename.endsWith(".jpg")) {
                return ResultUtils.error("文件类型不对");
            }

            String format = dateFormat.format(new Date());
            //realPath为文件保存的位置
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/img" + format;
            realPath = realPath.substring(1);//去掉第一个/符号
            File folder = new File(realPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            String newName;
            if (filename.endsWith(".png"))
                newName = UUID.randomUUID().toString() + ".png";
            else
                newName = UUID.randomUUID().toString() + ".jpg";
            try {
                //新建文件
                file.transferTo(new File(folder, newName));
                //String url = realPath + newName;
            } catch (IOException e) {
                return ResultUtils.error(e.getMessage());
            }

            //返回可供外界访问的url
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + newName;
            return ResultUtils.success("图片上传成功", url);


        }catch (Exception e){
            e.printStackTrace();
            return ResultUtils.error("图片上传失败" + e.getMessage());
        }

    }
}

